                                                                                                                                                                                                                                                                                                                                                                    package org.sjm.samples.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.sjm.samples.model.CommonMessageResultVO;
import org.sjm.samples.model.ExamScoreVO;
import org.sjm.samples.model.ExamStudentVO;
import org.sjm.samples.model.ExamSubjectVO;
import org.sjm.samples.model.ExamTestTypeVO;
import org.sjm.samples.model.ExamTestVO;
import org.sjm.samples.model.ExamUserVO;
import org.sjm.samples.model.PagerModel;
import org.sjm.samples.service.ITeacherService;
import org.sjm.samples.service.ISubjectService;
import org.sjm.samples.service.IUserService;
import org.sjm.samples.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;

@Controller
@RequestMapping(value = "/teacher")
public class TeacherController {
	
	@Autowired
	private ITeacherService teacherService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ISubjectService subjectService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@ModelAttribute
	public ExamTestVO getExamTestVO(){
		return new ExamTestVO();
	}
	
	@RequestMapping(value = "/testChangeLocale")
	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:toManageTest";
	}
	
/*	@RequestMapping(value = "/toManageTest")
	public String toManageTest(Model model){
		List<ExamTestVO> testList = teacherService.findAllTests();
		model.addAttribute("testList", testList);
		return "teacher/manageTest";
	}*/
	
	@RequestMapping(value = "/toManageTest")
	public String toPagerManageTest(Model model){
		PagerModel<ExamTestVO> page = teacherService.findAllByPage();
		model.addAttribute("page", page);
		return "teacher/manageTest";
	}
	
	@RequestMapping(value = "/toManageStudents")
	public String toManageStudents(Model model){
		List<ExamStudentVO> studentList = teacherService.getStudentList();
		model.addAttribute("studentList", studentList);
		return "teacher/manageStudent";
	}
	
	@RequestMapping(value = "/toManageScore")
	public String toManageScore(Model model){
		List<ExamScoreVO> scoreList = teacherService.getScoreList();
		model.addAttribute("scoreList", scoreList);
		return "teacher/manageScore";
	}
	
	@RequestMapping("/toManageUser")
	public String Users(Model model){
		List<ExamUserVO> list = userService.findAllStudents();
		for(ExamUserVO user : list){
			if("0".equals(user.getGender())){
				user.setGender("男");
			}else if("1".equals(user.getGender())){
				user.setGender("女");
			}else{
				user.setGender("");
			}
		}
		model.addAttribute("studentList", list);
		return "teacher/manageUser";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getSubjectAndTypes")
	public Map<String, Object> getSubjectAndTypes(){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ExamSubjectVO> subjectList = teacherService.getSubjectList();
		List<ExamTestTypeVO> testTypeList = teacherService.getTestTypeList();
		
		resultMap.put("subjectList", subjectList);
		resultMap.put("testTypeList", testTypeList);
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveTest", method = RequestMethod.POST)
	public CommonMessageResultVO saveTest(@Valid ExamTestVO examTestVO, BindingResult bindingResult){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		if(bindingResult.hasErrors()){
			List<ObjectError> errorList = bindingResult.getAllErrors();
			for(ObjectError error : errorList){
				FieldError fe = (FieldError) error;
				messageMap.put(fe.getField(), fe.getDefaultMessage());
			}
			resultVO.setMessageMap(messageMap);
			return resultVO;
		}
		try{
			teacherService.createTest(examTestVO);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateTest", method = RequestMethod.POST)
	public CommonMessageResultVO updateTest(@Valid ExamTestVO examTestVO, BindingResult bindingResult){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		if(bindingResult.hasErrors()){
			List<ObjectError> errorList = bindingResult.getAllErrors();
			for(ObjectError error : errorList){
				FieldError fe = (FieldError) error;
				messageMap.put(fe.getField(), fe.getDefaultMessage());
			}
			resultVO.setMessageMap(messageMap);
			return resultVO;
		}
		try{
			teacherService.editTest(examTestVO);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/deleteTest", method = RequestMethod.POST)
	public CommonMessageResultVO deleteTest(Integer testId){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		try{
			teacherService.deleteTest(testId);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getTestById", method = RequestMethod.POST)
	public ExamTestVO getTestById(Integer testId){
		ExamTestVO resultVO = teacherService.getTestById(testId);
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile")
	public CommonMessageResultVO uploadFile(@RequestParam(value = "uploadFile") MultipartFile[] uploadFile, HttpSession session, Model model){
//		final String FILE_SYSTEM_PATH = "F:\\upload\\";
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
//		File file = new File(FILE_SYSTEM_PATH);
		String fileName = uploadSimpleFile.getOriginalFilename();
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		Map<String, String> messageMap = new HashMap<String, String>();
		try{
			//鍒ゆ柇鏂囦欢绫诲瀷鍙兘鏄痻lsx锛� xls
			if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
				userService.saveStudentByExcel(uploadSimpleFile.getInputStream(), postfix);
				resultVO.setSuccess(true);
			}else{
				messageMap.put("message", "文件格式不符合");
				resultVO.setMessageMap(messageMap);
			}
			
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getAllSubject", method = RequestMethod.POST)
	public Map<String, Object> getAllSubject(String userId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("allSubject", subjectService.findAllSubjects());
		resultMap.put("selectedSubject", subjectService.getSubjectsByUserId(userId));
		resultMap.put("testSubject", subjectService.getSubjectsByTest(userId));
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/subjectEditStatus", method = RequestMethod.POST)
	public CommonMessageResultVO subjectEditStatus(Integer subId){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		try{
			String message = subjectService.editSubjectStatus(subId);
			messageMap.put("message", message);
			resultVO.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
		}
		resultVO.setMessageMap(messageMap);
		return resultVO;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getAllStudent", method = RequestMethod.POST)
	public Map<String, Object> getAllStudent(Integer subId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("allUser", teacherService.getStudentList());
		resultMap.put("selectedUser", subjectService.getAllUserSubject(subId));
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveSubjectStudent", method = RequestMethod.POST)
	public Map<String, Object> saveSubjectStudent(@RequestParam(name = "subjectStudents[]")String[] subjectStudents, Integer subId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", false);
		
		List<String> list = new ArrayList<String>();
		for(String student : subjectStudents){
			list.add(student);
		}
		try {
			subjectService.saveSubjectStudent(list, subId);
			resultMap.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveStudentSubject", method = RequestMethod.POST)
	public Map<String, Object> saveStudentSubject(@RequestParam(name = "studentSubjects[]")Integer[] studentSubjects, String userId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", false);
		
		List<Integer> list = new ArrayList<Integer>();
		for(Integer subject : studentSubjects){
			list.add(subject);
		}
		try {
			subjectService.saveStudentSubject(list, userId);
			resultMap.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getScore", method = RequestMethod.POST)
	public Map<String, Object> getScore(String condition, String query){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", false);
		List<ExamScoreVO> resultList;
		try {
			resultList = teacherService.getScore(condition, query);
			if(resultList.size() > 0){
				resultMap.put("resultList", resultList);
				resultMap.put("success", true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
}
